import Vue from "vue";
import Vuex from "vuex";
import discussion from "./discussion";
import team from "./team";
import message from "./message";
import task from "./task";
import search from "./search";
import { getTagsMinDistance } from "../utils/tagsMinDistance";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    userInfo: {}, // 个人用户信息
    teamLeader: {},
    taskTeam: {},
    userList: [], // 首页用户列表
    userListByTags: [], // 匹配用户标签的列表
    noticeList: [],
    userDiscussion: [], // 用户的讨论内容
    userFocus: [], // 用户的关注
    userTaskList: [], // 除去分配给我的列表
    collectionDiscussion: [], // 用户收藏的讨论内容
    teamMember: [], // 队伍成员
    userTeam: [], // 自己的队伍
    joinTeam: [], // 自己加入的队伍
  },

  mutations: {
    // 设置用户信息
    setUserInfo(state, value) {
      state.userInfo = value;
      console.log("拿到用户信息：", value);
    },

    // 设置队长用户信息
    setTeamLeader(state, value) {
      state.teamLeader = value;
    },
    // 设置头像信息
    setUserAvatar(state, value) {
      state.userInfo.avatar = value;
    },

    // 设置昵称
    setUserNickName(state, value) {
      state.userInfo.nickName = value;
    },
    // 处理收藏/取消收藏操作
    setUserCollection(state, payload) {
      const { isCollection, discussionId } = payload,
        userInfo = state.userInfo;
      if (isCollection) {
        userInfo.collection.push(discussionId);
      } else {
        userInfo.collection = userInfo.collection.filter(
          (item) => item != discussionId
        );
        state.collectionDiscussion = state.collectionDiscussion.filter(
          (item) => item._id != discussionId
        );
      }
    },

    // 获取用户消息列表
    setUserNotice(state, value) {
      state.noticeList = value;
    },
    // 发布新讨论时用户信息同时也要添加
    setUserDiscussionCount(state, id) {
      state.userInfo.discussion.push(id);
    },

    // 创建新队伍时用户信息同时也要添加
    setUserTeamCount(state, id) {
      state.userInfo.myTeam.push(id);
    },

    // 设置任务队伍详细信息
    setTaskTeam(state, value) {
      state.taskTeam = value;
    },

    // 保存个人信息
    setPersonalInfo(state, info) {
      state.userInfo.nickName = info.nickName;
      state.userInfo.school = info.school;
      state.userInfo.area = info.area;
      state.userInfo.grade = info.grade;
      state.userInfo.cls = info.cls;
      state.userInfo.qq = info.qq;
      state.userInfo.wx = info.wx;
      state.userInfo.introduce = info.introduce;
      state.userInfo.tags = info.tags;
    },

    // 设置首页用户列表信息
    setUserListContent(state, list) {
      state.userList = [...state.userList, ...list];
    },
    // 设置首页标签匹配用户列表
    setUserListComputed(state, list) {
      state.userListByTags = list;
    },

    // 清空残留的用户列表
    clearUserList(state) {
      state.userList = [];
    },

    // 设置用户关注列表
    addtUserFocus(state, item) {
      state.userFocus.push(item);
    },

    // 拿到个人用户的讨论信息
    addUserDiscussion(state, item) {
      state.userDiscussion.push(item);
    },
    // 拿到个人用户收藏的讨论信息
    addUserCollectionDiscussion(state, item) {
      state.collectionDiscussion.push(item);
    },

    // 拿到个人用户的任务列表
    addUserTaskList(state, item) {
      state.userTaskList.push(item);
    },
    // 移除一个指定的讨论（个人删除讨论）
    deleteOneDiscussion(state, discussionId) {
      state.userDiscussion = state.userDiscussion.filter(
        (item) => item._id !== discussionId
      );
      state.userInfo.discussion = state.userInfo.discussion.filter(
        (item) => item._id !== discussionId
      );
    },
    // 拿到个人用户的队伍信息
    addUserTeam(state, item) {
      state.userTeam.push(item);
    },

    // 清除我的队伍里的列表
    clearUserTeam(state) {
      state.userTeam = [];
    },

    // 拿到个人用户加入的队伍信息
    addUserJoinTeam(state, item) {
      state.joinTeam.push(item);
    },

    // 获取队员信息
    addTeamMember(state, item) {
      state.teamMember.push(item);
    },

    // 先清空队员信息
    clearTeamMember(state) {
      state.teamMember = [];
    },

    // 清空我的任务列表信息
    clearUserTaskList(state) {
      state.userTaskList = [];
    },
    // 清空残留的讨论信息
    clearUserDiscussion(state) {
      state.userDiscussion = [];
    },
    // 清空关注列表信息
    clearUserFocus(state) {
      state.userFocus = [];
    },
  },
  actions: {
    // 获取个人用户信息
    getUserInfo({ commit, state }, payload) {
      const db = wx.cloud.database(),
        { type, userId } = payload,
        _openid = state.userInfo._openid;
      // type: 0 获取自己信息   1 获取队长信息  2 获取队员信息 3 获取关注他人的信息
      return new Promise(async (resolve, reject) => {
        try {
          if (type === 0) {
          }
          const res =
            type === 0
              ? await db.collection("user").where({ _openid }).get()
              : await db.collection("user").where({ _openid: userId }).get();
          if (type === 0 || type === 4) {
            commit("setUserInfo", res.data[0]);
          } else if (type === 1) {
            commit("setTeamLeader", res.data[0]);
          } else if (type === 2) {
            commit("addTeamMember", res.data[0]);
          } else if (type === 3) {
            commit("addtUserFocus", res.data[0]);
          }

          resolve(res.data[0]);
        } catch (err) {
          console.log("获取用户信息失败：", err);
          reject(err);
        }
      });
    },
    // 上传头像信息
    uploadUserAvatar({ commit, state }, value) {
      const openId = state.userInfo._openid,
        db = wx.cloud.database();
      console.log("查看id:", openId);
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: openId })
            .update({
              data: {
                avatar: value,
              },
            });
          console.log("查看头像上传：", res);
          commit("setUserAvatar", value);
          console.log("头像上传成功！", value);
          resolve(value);
        } catch (err) {
          console.log("上传失败：", err);
          reject(err);
        }
      });
    },

    // 头像上传至云存储
    uploadAvatarFileToCloud({ dispatch }, payload) {
      const { fileName, filePath } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await wx.cloud.uploadFile({
            cloudPath: fileName,
            filePath,
          });
          console.log(res);
          await dispatch("uploadUserAvatar", res.fileID);
          resolve("成功");
        } catch (err) {
          console.log("头像上传失败:", err);
          reject(err);
        }
      });
    },
    // 上传昵称
    uploadUserNickName({ commit, state }, value) {
      const openId = state.userInfo._openid,
        db = wx.cloud.database();
      console.log("查看id:", openId);
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: openId })
            .update({
              data: {
                nickName: value,
              },
            });
          console.log("查看昵称上传：", res);
          commit("setUserNickName", value);
          console.log("昵称修改成功！", value);
          resolve(value);
        } catch (err) {
          console.log("修改失败：", err);
          reject(err);
        }
      });
    },

    // 收藏/取消讨论内容
    handleCollectionDiscussion({ commit, state }, payload) {
      // isCollection判断收藏或者取消收藏
      const { isCollection, discussionId } = payload,
        value = isCollection ? 1 : -1,
        operator = isCollection ? "push" : "pull",
        db = wx.cloud.database(),
        _ = db.command;
      return new Promise(async (resolve, reject) => {
        const userId = state.userInfo._openid;
        try {
          const res1 = await db
            .collection("discussion")
            .where({ _id: discussionId })
            .update({
              data: {
                collection: _.inc(value),
              },
            });
          const res2 = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                collection: _[operator](discussionId),
              },
            });
          commit("setUserCollection", payload);
          resolve("收藏/取消收藏成功");
        } catch (err) {
          console.log("收藏/取消收藏失败：", err);
          reject(err);
        }
      });
    },

    // 添加评论
    addDiscussionComment({ commit, state }, payload) {
      const { comment, discussionId } = payload,
        db = wx.cloud.database(),
        _ = db.command;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("discussion")
            .where({ _id: discussionId })
            .update({
              data: {
                commentCount: _.inc(1),
                commentList: _.push(comment),
              },
            });
          console.log("查看评论结果：", res);
          commit("m_discussion/addCurrentDiscussionComment", comment);
          resolve("评论成功");
        } catch (err) {
          console.log("评论出错：", err);
          reject(err);
        }
      });
    },

    // 个人发布讨论，将讨论信息保存至个人信息中
    publishDiscussionContent({ commit, state }, id) {
      const userId = state.userInfo._openid,
        db = wx.cloud.database(),
        _ = db.command;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                discussion: _.push(id),
              },
            });
          commit("setUserDiscussionCount", id);
          resolve("发布成功");
        } catch (err) {
          console.log("发布出错：", err);
          reject(err);
        }
      });
    },

    // 个人创建队伍，将队伍信息保存至个人信息中
    publishTeamContent({ commit, state }, id) {
      const userId = state.userInfo._openid,
        db = wx.cloud.database(),
        _ = db.command;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                myTeam: _.push(id),
              },
            });
          commit("setUserTeamCount", id);
          resolve("创建成功");
        } catch (err) {
          console.log("创建出错：", err);
          reject(err);
        }
      });
    },

    // 保存设置的个人信息
    savePersonalInfo({ commit, state }, info) {
      const userId = state.userInfo._openid,
        db = wx.cloud.database(),
        _ = db.command;
      console.log("查看id:", userId);
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: info,
            });
          console.log("查看保存的信息：", res);
          commit("setPersonalInfo", info);
          resolve("保存个人信息");
        } catch (err) {
          console.log("保存出错：", err);
          reject(err);
        }
      });
    },

    // 首页获取用户列表
    getUserList({ commit }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { page, limitCount } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .orderBy("createTime", "desc")
            .where(
              _.or([
                {
                  qq: _.neq(""),
                },
                {
                  wx: _.neq(""),
                },
              ])
            )
            .skip(page * limitCount)
            .limit(limitCount)
            .get();
          commit("setUserListContent", res.data);
          resolve("获取成功");
        } catch (err) {
          console.log("获取用户列表失败：", err);
          reject(err);
        }
      });
    },

    // 获取与用户标签匹配的用户列表
    getUserListByTags({ commit }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { tags } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .orderBy("createTime", "desc")
            .where(
              _.or([
                {
                  qq: _.neq(""),
                },
                {
                  wx: _.neq(""),
                },
              ])
            )
            .get();

          // getTagsMinDistance
          const userList = res.data;
          userList.forEach((item) => {
            item.tagsPower = getTagsMinDistance(tags, item.tags);
          });
          userList.sort((a, b) => a.tagsPower - b.tagsPower);
          console.log("标签获取数据：", userList);
          commit(
            "setUserListComputed",
            userList.filter((item) => item.tagsPower !== tags.length)
          );
          resolve("获取成功");
        } catch (err) {
          console.log("获取用户列表失败：", err);
          reject(err);
        }
      });
    },

    // 获取用户消息列表
    getUserNoticeList({ commit, state }) {
      const db = wx.cloud.database(),
        userId = state.userInfo._openid;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("notice")
            .where({
              "author['_openid']": userId,
            })
            .get();
          console.log("获取消息列表：", res.data);
          commit("setUserNotice", res.data);
          resolve("获取成功");
        } catch (err) {
          console.log("获取消息失败：", err);
          reject(err);
        }
      });
    },

    // 关注/取关他人（成为粉丝）
    focusUser({ commit, state }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { focusId, isFocus } = payload,
        operator = isFocus ? "push" : "pull",
        userId = state.userInfo._openid;
      console.log(userId, focusId);
      return new Promise(async (resolve, reject) => {
        try {
          const res1 = await db
            .collection("user")
            .where({ _openid: focusId })
            .update({
              data: {
                fans: _[operator](userId),
              },
            });
          const res2 = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                focusList: _[operator](focusId),
              },
            });
          resolve("关注成功");
        } catch (err) {
          console.log("关注失败:", err);
          reject(err);
        }
      });
    },

    // 获取个人用户单条讨论数据（我的 + 收藏）
    getOneUserDiscussion({ commit }, payload) {
      const db = wx.cloud.database(),
        { discussionId, type } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("discussion")
            .where({ _id: discussionId })
            .get();
          if (type === "myDiscussion") {
            commit("addUserDiscussion", res.data[0]);
          } else if (type === "myCollection") {
            commit("addUserCollectionDiscussion", res.data[0]);
          }
          resolve("获取成功");
        } catch (err) {
          console.log("获取单条错误:", err);
          reject(err);
        }
      });
    },

    // 获取个人用户单条队伍数据
    getOneUserTeam({ commit }, payload) {
      const db = wx.cloud.database(),
        { teamId, type } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("team").where({ _id: teamId }).get();
          if (type === "myTeam") {
            commit("addUserTeam", res.data[0]);
          } else if (type === "joinTeam") {
            commit("addUserJoinTeam", res.data[0]);
          } else if (type === "taskTeam") {
            commit("setTaskTeam", res.data[0]);
          }
          resolve("获取成功");
        } catch (err) {
          console.log("获取单条错误:", err);
          reject(err);
        }
      });
    },

    // 获取个人信息任务列表单条数据
    getOneUserTaskList({ commit }, taskId) {
      const db = wx.cloud.database();
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("taskList")
            .where({ _id: taskId })
            .get();
          commit("addUserTaskList", res.data[0]);
          resolve("获取成功");
        } catch (err) {
          console.log("获取任务列表失败：", err);
          reject(err);
        }
      });
    },

    // 删除user表中的一个讨论
    deleteMyDiscussion({ commit, state }, discussionId) {
      const db = wx.cloud.database(),
        _ = db.command,
        userId = state.userInfo._openid;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                discussion: _.pull(discussionId),
              },
            });
          commit("deleteOneDiscussion", discussionId);
          resolve("删除个人讨论成功");
        } catch (err) {
          console.log("删除个人讨论失败：", err);
          reject(err);
        }
      });
    },

    // 添加任务列表至个人信息
    addTaskToUser({ state }, taskListId) {
      const db = wx.cloud.database(),
        _ = db.command,
        userId = state.userInfo._openid;
      return new Promise(async (resolve, reject) => {
        try {
          await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                taskList: _.push(taskListId),
              },
            });
          resolve("添加成功");
        } catch (err) {
          console.log("添加任务至个人信息失败：", err);
          reject(err);
        }
      });
    },

    // 将任务列表从个人信息中移除
    removeTaskToUser({ state }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { listId, isTeam } = payload,
        userId = state.userInfo._openid;
      const field = isTeam ? "teamTaskList" : "taskList";
      return new Promise(async (resolve, reject) => {
        try {
          await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                [field]: _.pull(listId),
              },
            });
          resolve("移除任务信息成功");
        } catch (err) {
          console.log("个人信息移除任务失败：", err);
          reject(err);
        }
      });
    },

    // 添加用户消息
    addUserNotice({ commit, state }, payload) {
      const db = wx.cloud.database(),
        receiveObj = {},
        { content, type } = payload;
      receiveObj._openid = state.userInfo._openid;
      receiveObj.nickName = state.userInfo.nickName;
      receiveObj.avatar = state.userInfo.avatar;
      return new Promise(async (resolve, reject) => {
        const item = {};
        item.receiveObj = receiveObj;
        item.content = content;
        item.type = type;
        item.createTime = new Date();
        item.isView = false;
        try {
          const res = await db.collection("notice").add({
            data: item,
          });
          resolve("保存消息成功");
        } catch (err) {
          console.log("保存消息失败", err);
          reject(err);
        }
      });
    },
  },
  modules: {
    m_discussion: discussion,
    m_team: team,
    m_message: message,
    m_task: task,
    m_search: search,
  },
});

export default store;
